<?php


namespace app\api\controller\Course;


use app\api\controller\AppController;
use app\api\model\Course\CourseModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\System\SysSettingModel;
use app\api\model\User\UserCouponModel;
use app\api\model\User\UserWalletModel;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use app\Utils\WechatPayUtil;
use Exception;
use think\facade\Db;

class CourseOrder extends AppController
{

    /**
     * @api {post} /pre_course_order_info 课程报名预创建订单信息 (根据传入优惠券重新请求接口)
     * @apiGroup 课程
     * @apiParam {string} token Token
     * @apiParam {int} id 课程ID
     * @apiParam {string} mobile 手机号 开始进入默认空
     * @apiParam {string} real_name 姓名 开始进入默认空
     * @apiParam {string} address 地址 开始进入默认空
     * @apiParam {int} user_coupon_id 优惠券ID 开始进入默认0
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccessExample {json} 部分数据
     * {
     *   "id":"课程ID",
     *   "course":"课程信息",
     *   "mobile":"手机号",
     *   "real_name":"姓名",
     *   "address":"地址",
     *   "total_price":"总金额",
     *   "deduction_price":"优惠金额",
     *   "user_coupon_id":"选择的优惠券ID",
     *   "user_coupon_list":"当前课程，用户可用的优惠券列表"
     * }
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function preCourseOrderInfo(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $id = !empty($param['id']) ? $param['id'] : 0;
        $type = !empty($param['type']) ? $param['type'] : 0; // 0 普通 1 拼团
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $real_name = !empty($param['real_name']) ? $param['real_name'] : "";
        $address = !empty($param['address']) ? $param['address'] : "";
        //用户优惠券ID
        $user_coupon_id = !empty($param['user_coupon_id']) ? $param['user_coupon_id'] : 0;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }

        //当前商品用户的优惠券列表
        $user_coupon_list = [];
        $cou_where = [
            ['uid', '=', $user['id']],
            ['label', '=', 1],
            ['type', '=', 2],
            ['goods_ids', 'like', '%' . $id . ',' . '%'],
            ['start_time', '<', date("Y-m-d H:i:s", time())],
            ['end_time', '>', date("Y-m-d H:i:s", time())],
            ['status', '=', 0]
        ];
        $cou_where_1 = [
            ['uid', '=', $user['id']],
            ['type', '=', 1],
            ['label', '=', 1],
            ['start_time', '<', date("Y-m-d H:i:s", time())],
            ['end_time', '>', date("Y-m-d H:i:s", time())],
            ['status', '=', 0]
        ];
        $coupon_list = UserCouponModel::getUserCouponWhereOrMore([$cou_where, $cou_where_1]);
        foreach ($coupon_list as $item) {
            $coupon_data = json_decode($item['coupon_data'], true);
            $array['id'] = $item['id'];
            $array['uid'] = $item['uid'];
            $array['coupon_id'] = $item['coupon_id'];
            $array['coupon_title'] = $coupon_data['coupon_title'];
            $array['status'] = $item['status'];
            $array['goods_ids'] = $item['goods_ids'];
            $array['amount'] = $item['amount'];
            $array['total_amount'] = $item['total_amount'];
            $array['start_time'] = $item['start_time'];
            $array['end_time'] = $item['end_time'];
            array_push($user_coupon_list, $array);
        }
        unset($item);


        $where = [
            ['id', '=', $id],
            //['start_time','<=',date("Y-m-d H:i:s",time())],
            //['end_time','>=',date("Y-m-d H:i:s",time())],
        ];
        $course = CourseModel::getCourseWhere($where, 'id,title,img,price,cost_price,vip_price,start_time,end_time,school_id,start_time,end_time');
        if (!empty($course)) {
            $or_where = [
                ['o.uid', '=', $user['id']],
                ['o.type', '=', 3],
                ['og.type', '=', 3],
                ['o.status', '<>', 4],
                ['o.status', '<>', -1],
                ['og.goods_id', '=', $id],
                ['o.add_time', '>=', $course['start_time']],
                ['o.add_time', '<=', $course['end_time']],
            ];
            $course_order_count = OrderModel::getOrderWhereJoinMore($or_where);
            if (count($course_order_count) > 0) {
                return Util::returnJson(self::CODE_ERROR, null, "请不要重复参加");
            }

            $price = 0;
            if ($type == 0) {
                //价格
                if (!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time())) {
                    //VIP
                    $price = $course['vip_price'];
                } else {
                    $price = $course['price'];
                }
            } else {
                $price = $course['deposit']; //押金
            }

            //总金额
            $total_price = $price;
            //优惠金额
            $deduction_price = 0;

            if (!empty($user_coupon_id)) {
                //有使用优惠券
                $user_coupon = UserCouponModel::getUserCouponWhere([['id', '=', $user_coupon_id]]);
                if ($user_coupon['label'] == 1) {
                    if (strtotime($user_coupon['start_time']) < time() && strtotime($user_coupon['end_time']) < time()) {
                        if (empty($user_coupon['status'])) {
                            if ($user_coupon['attr'] == 1) {
                                //立减
                                $deduction_price += $user_coupon['amount'];
                                $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                            }
                            if ($user_coupon['attr'] == 2) {
                                //满减
                                if ($total_price > $user_coupon['total_amount']) {
                                    $deduction_price += $user_coupon['amount'];
                                    $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                                }
                            }
                            if ($user_coupon['attr'] == 3) {
                                //立减折扣(打折)
                                $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                $deduction_price += bcsub($total_price, $amount, 2);
                                $total_price = $amount;
                            }
                            if ($user_coupon['attr'] == 4) {
                                //满减折扣(打折)
                                if ($total_price > $user_coupon['total_amount']) {
                                    $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                    $deduction_price += bcsub($total_price, $amount, 2);
                                    $total_price = $amount;
                                }
                            }
                        } else {
                            return Util::returnJson(self::CODE_ERROR, null, "优惠券已使用或已过期");
                        }
                    } else {
                        return Util::returnJson(self::CODE_ERROR, null, "优惠券已过期");
                    }
                } else {
                    return Util::returnJson(self::CODE_ERROR, null, "优惠券类型错误");
                }
            }

            //总报名人数
            $or_where = [
                ['o.type', '=', 3],
                ['og.type', '=', 3],
                ['o.status', '<>', 4],
                ['o.status', '<>', -1],
                ['og.goods_id', '=', $id],
                ['o.add_time', '>=', $course['start_time']],
                ['o.add_time', '<=', $course['end_time']],
            ];
            $course['course_all_count'] = count(OrderModel::getOrderWhereJoinMore($or_where));
            $course['img'] = ImageUtil::i()->replaceUrl($course['img']);
            $data = [
                'token' => $param['token'],
                'id' => $id,
                'course' => $course,
                'mobile' => $mobile,
                'real_name' => $real_name,
                'address' => $address,
                'total_price' => $total_price,
                'deduction_price' => !empty($deduction_price) ? $deduction_price : 0,
                'user_coupon_id' => $user_coupon_id,//优惠券ID
                'user_coupon_list' => $user_coupon_list, //当前课程用户的优惠券
                'course_all_count' => $course['course_all_count']
            ];
            return Util::returnJson(self::CODE_SUCCESS, $data, "");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "课程不存在");
        }
    }

    /**
     * @api {post} /create_course_order 课程报名
     * @apiGroup 课程
     * @apiParam {string} token Token
     * @apiParam {int} id 课程ID
     * @apiParam {string} mobile 手机号
     * @apiParam {string} real_name 姓名
     * @apiParam {string} address 地址
     * @apiParam {int} user_coupon_id 优惠券ID
     * @apiParam {int} pay_way 支付类型  2:支付宝 3：微信
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function createCourseOrder(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $id = !empty($param['id']) ? $param['id'] : 0;
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $real_name = !empty($param['real_name']) ? $param['real_name'] : "";
        $address = !empty($param['address']) ? $param['address'] : "";
        $user_coupon_id = !empty($param['user_coupon_id']) ? $param['user_coupon_id'] : 0;
        $type = !empty($param['type']) ? $param['type'] : 0;  //是否拼团  0 否 1是
        if (empty($user) || !isset($user)) {
            return Util::returnJson(self::CODE_ERROR, null, "请重新登录");
        }

        if (!in_array($param['pay_way'], [2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "支付类型错误");
        }

        $where = [
            ['id', '=', $id],
            //['start_time','<=',date("Y-m-d H:i:s",time())],
            //['end_time','>=',date("Y-m-d H:i:s",time())],
        ];
        $course = CourseModel::getCourseWhere($where);
        if (!empty($course)) {
            $or_where = [
                ['o.uid', '=', $user['id']],
                ['o.type', '=', 3],
                ['og.type', '=', 3],
                ['o.status', '<>', 4],
                ['o.status', '<>', -1],
                ['og.goods_id', '=', $id],
                ['o.add_time', '>=', $course['start_time']],
                ['o.add_time', '<=', $course['end_time']],
            ];
            $course_order_count = OrderModel::getOrderWhereJoinMore($or_where);
            if (count($course_order_count) > 0) {
                return Util::returnJson(self::CODE_ERROR, null, "请不要重复参加");
            }

            $price = 0;

            if ($type == 0) {
                //价格
                if (!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time())) {
                    //VIP
                    $price = $course['vip_price'];
                } else {
                    $price = $course['price'];
                }
            } else {
                $price = $course['deposit']; //押金
            }
            //总金额
            $total_price = $price;
            //优惠金额
            $deduction_price = 0;

            if (!empty($user_coupon_id)) {
                //有使用优惠券
                $user_coupon = UserCouponModel::getUserCouponWhere([['id', '=', $user_coupon_id]]);
                if ($user_coupon['label'] == 1) {
                    if (strtotime($user_coupon['start_time']) < time() && strtotime($user_coupon['end_time']) > time()) {
                        if (empty($user_coupon['status'])) {
                            if ($user_coupon['attr'] == 1) {
                                //立减
                                $deduction_price += $user_coupon['amount'];
                                $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                            }
                            if ($user_coupon['attr'] == 2) {
                                //满减
                                if ($total_price > $user_coupon['total_amount']) {
                                    $deduction_price += $user_coupon['amount'];
                                    $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                                }
                            }
                            if ($user_coupon['attr'] == 3) {
                                //立减折扣(打折)
                                $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                $deduction_price += bcsub($total_price, $amount, 2);
                                $total_price = $amount;
                            }
                            if ($user_coupon['attr'] == 4) {
                                //满减折扣(打折)
                                if ($total_price > $user_coupon['total_amount']) {
                                    $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                    $deduction_price += bcsub($total_price, $amount, 2);
                                    $total_price = $amount;
                                }
                            }
                        } else {
                            return Util::returnJson(self::CODE_ERROR, null, "优惠券已使用或已过期");
                        }
                    } else {
                        return Util::returnJson(self::CODE_ERROR, null, "优惠券已过期");
                    }
                } else {
                    return Util::returnJson(self::CODE_ERROR, null, "优惠券类型错误");
                }
            }

            //订单号
            $order_sn = StrUtil::i()->getOrderSn();
            $data_order = [
                'uid' => $user['id'],
                'order_sn' => $order_sn,
                'type' => 3,
                'total_price' => $total_price,
                'deduction_price' => !empty($deduction_price) ? $deduction_price : 0,
                'mobile' => $mobile,
                'username' => $real_name,
                'address' => $address,
                'pay_way' => $param['pay_way'],
                'source_type' => 1,
                'pay_num' => 1,
                'status' => 0,
                'is_group' => $type,
                'user_coupon_id' => !empty($user_coupon_id) ? $user_coupon_id : 0,
                'up_time' => date("Y-m-d H:i:s", time()),
                'add_time' => date("Y-m-d H:i:s", time()),
                'mer_id' => $course['mer_id'],
            ];

            Db::startTrans();
            try {
                //商户订单号
                $out_trade_no = StrUtil::i()->getOrderSn(3);
                $order_id = OrderModel::addOrder($data_order);
                if ($order_id) {
                    $data_goods_order = [
                        'order_id' => $order_id,
                        'type' => $data_order['type'],
                        'goods_id' => $course['id'],
                        'number' => $data_order['pay_num'],
                        'goods_info' => json_encode($course),
                        'goods_price' => $price,
                        'total_price' => $data_order['total_price'],
                        'deduction_price' => $data_order['deduction_price'],
                        'up_time' => date("Y-m-d H:i:s", time()),
                        'add_time' => date("Y-m-d H:i:s", time()),
                        "mer_id" => $course['school_id'],
                        "ratio" => !empty($course['merchant_ratio']) ? $course['merchant_ratio'] : 0,
                    ];
                    $id = OrderGoodsModel::addOrderGoods($data_goods_order);
                    if ($id) {
                        if (!empty($user_coupon_id)) {
                            $user_coupon_save = [
                                'status' => 1,
                                'up_time' => date("Y-m-d H:i:s", time())
                            ];
                            UserCouponModel::updateUserCouponWhere([['id', '=', $user_coupon_id]], $user_coupon_save);
                        }
                    }
                    $result1=null;
                    $result = null;
                    //支付
                    if ($param['pay_way'] == 1) {
                        //余额支付
                    } else if ($param['pay_way'] == 2) {
                        $order_save = [
                            'out_trade_no' => $out_trade_no
                        ];
                        OrderModel::updateOrderWhere([['id', '=', $order_id]], $order_save);
                        //支付宝支付
                        $result = $this->aliPay($data_order['total_price'], $out_trade_no, "购买课程");

                    } else if ($param['pay_way'] == 3) {
                        //微信支付
                        $order_save = [
                            'out_trade_no' => $out_trade_no
                        ];
                        OrderModel::updateOrderWhere([['id', '=', $order_id]], $order_save);
                        $wx = new WechatPayUtil();
                        $result1 = $wx->wechat_pay($out_trade_no, $data_order['total_price'], '购买课程支付');

                    }

                    if ($result['code'] == 0) {
                        $data = [
                            'pay_way' => $param['pay_way'],
                            'pay_info' => $result?$result['data']:'',
                            'wx_pay' => $result1
                        ];
                        //提交保存
                        Db::commit();
                        return Util::returnJson(self::CODE_SUCCESS, $data, "下单成功");
                    } else {
                        Db::rollback();
                        return Util::returnJson(self::CODE_ERROR, null, $result['msg']);
                    }
                } else {
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR . null, "报名失败");
                }
            } catch (Exception $e) {
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR . null, "报名失败");
            }
        } else {
            return Util::returnJson(self::CODE_ERROR . null, "报名已结束");
        }
    }

}